<template>
  <div class="device-management">
    
    <div class="management-content">
      <div class="search-container">
        <div class="search-left">
          <el-input
            v-model="searchQuery"
            placeholder="请输入设备名称或设备ID搜索"
            class="search-input"
            @input="handleSearch"
          />
          <el-select
            v-model="selectedStatus"
            placeholder="请选择设备状态"
            class="search-select"
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="未认证" value="0" />
            <el-option label="认证" value="1" />
            <el-option label="启用" value="2" />
            <el-option label="未启用" value="3" />
          </el-select>
        </div>
        <el-button type="primary" class="primary-button" @click="showAddDialog">新增设备</el-button>
      </div>
      
      <el-table :data="devices" border>
        <el-table-column prop="id" label="ID" width="40" header-align="center" align="center" />
        <el-table-column prop="code" label="设备唯一码" width="120" header-align="center" />
        <el-table-column prop="name" label="设备名称" width="150" header-align="center" />
        <el-table-column prop="productCode" label="产品Code" width="150" header-align="center" align="center" />
        <el-table-column prop="productName" label="产品名称" width="150" header-align="center" align="center" />
        <el-table-column prop="status" label="状态" width="100" header-align="center" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accessMethod" label="接入方式" width="90" header-align="center" align="center" />
        <el-table-column prop="authMethod" label="认证方式" width="160" header-align="center" align="center" />
        <el-table-column prop="authPassword" label="认证密码" width="160" header-align="center" align="center">
          <template #default="scope">
            <div @click="togglePassword(scope.row, 'showPassword')">
              {{ scope.row.showPassword ? (scope.row.authPassword || '未设置') : '******' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" fixed="right" header-align="center" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button 
                v-if="scope.row.status === 0 || scope.row.status === '0' || scope.row.status === '未认证'"
                type="success" 
                size="small" 
                @click="handleAuthDevice(scope.row)"
              >
                认证
              </el-button>
              <el-button 
                v-else-if="scope.row.status === 1 || scope.row.status === '1' || scope.row.status === '认证' || scope.row.status === 2 || scope.row.status === '2' || scope.row.status === '启用'"
                type="info" 
                size="small" 
                disabled
              >
                已认证
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="toggleDeviceStatus(scope.row)"
                :disabled="scope.row.status === 0 || scope.row.status === '0' || scope.row.status === '未认证'"
              >{{ getToggleStatusLabel(scope.row.status) }}</el-button>
              <el-button type="primary" size="small" @click="editDevice(scope.row)">编辑</el-button>
              <el-dropdown 
                :disabled="scope.row.status !== 2 && scope.row.status !== '2' && scope.row.status !== '启用'"
                @command="(command) => handleDataOperationCommand(command, scope.row)"
              >
                <el-button type="primary" size="small">
                  数据操作
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="receive">接收信息</el-dropdown-item>
                    <el-dropdown-item command="send">发送信息</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button type="danger" size="small" @click="deleteDevice(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 新增/编辑设备对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900px">
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-form-item label="设备编码" prop="code" :rules="[{ required: true, message: '请输入设备编码', trigger: 'blur' }]">
          <el-input v-model="formData.code" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name" :rules="[{ required: true, message: '请输入设备名称', trigger: 'blur' }]">
          <el-input v-model="formData.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="所属产品" prop="productId">
          <!-- 在编辑模式下显示只读的产品名称 -->
          <el-input v-model="formData.productName" placeholder="暂无产品" disabled v-if="formData.id" />
          <!-- 在新增模式下仍然允许选择产品 -->
          <el-select v-model="formData.productId" placeholder="请选择所属产品" @change="onProductChange" v-else :rules="[{ required: true, message: '请选择所属产品', trigger: 'change' }]">
            <el-option v-for="product in products" :key="product.id" :label="product.name" :value="product.id" />
          </el-select>
        </el-form-item>

        <!-- 认证方式输入框 - 只在选择产品后显示 -->
        <el-form-item v-if="formData.hasSelectedProduct" label="认证方式" prop="authMethod">
          <el-input v-model="formData.authMethod" disabled></el-input>
        </el-form-item>

        <!-- 接入方式输入框 - 只在选择产品后显示 -->
        <el-form-item v-if="formData.hasSelectedProduct" label="接入方式" prop="accessMethod">
          <el-input v-model="formData.accessMethod" disabled></el-input>
        </el-form-item>
        <el-form-item label="认证密码" prop="authPassword" :rules="[{ required: true, message: '请输入认证密码', trigger: 'blur' }]">
          <el-input v-model="formData.authPassword" placeholder="请输入认证密码" show-password />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.comment" type="textarea" placeholder="请输入设备描述" />
        </el-form-item>
        
        <!-- 物模型展示列表 - 只在选择产品后显示 -->
        <el-form-item v-if="formData.hasSelectedProduct" label="" class="model-list-container">
          <h4>物模型属性</h4>
          <el-table :data="productProperties" border style="width: 100%; overflow-x: auto;">
            <el-table-column prop="property" label="属性">
              <template #default="scope">
                <el-input v-model="scope.row.property" placeholder="请输入属性" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
            <el-table-column prop="propertyName" label="属性名">
              <template #default="scope">
                <el-input v-model="scope.row.propertyName" placeholder="请输入属性名" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
            <el-table-column prop="dataType" label="数据类型">
              <template #default="scope">
                <el-select v-model="scope.row.dataType" placeholder="请选择数据类型" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'">
                  <el-option label="整数" value="integer" />
                  <el-option label="双精度" value="double" />
                  <el-option label="浮点数" value="float" />
                  <el-option label="字符串" value="string" />
                  <el-option label="布尔值" value="boolean" />
                  <el-option label="枚举" value="enum" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="dataRange" label="数据范围">
              <template #default="scope">
                <el-input v-model="scope.row.dataRange" placeholder="请输入数据范围" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
            <el-table-column prop="precisions" label="精度">
              <template #default="scope">
                <el-input v-model.number="scope.row.precisions" type="number" placeholder="请输入精度" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
            <el-table-column prop="accessMode" label="读取方式">
              <template #default="scope">
                <el-select v-model="scope.row.accessMode" placeholder="请选择读取方式" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'">
                  <el-option label="读" value="read" />
                  <el-option label="写" value="write" />
                  <el-option label="上报" value="report" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="属性值">
              <template #default="scope">
                <el-input v-model="scope.row.value" placeholder="请输入属性值" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
            <el-table-column prop="comment" label="描述">
              <template #default="scope">
                <el-input v-model="scope.row.comment" placeholder="请输入描述" :disabled="!formData.id || formData.status === 0 || formData.status === '0' || formData.status === '未认证'" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发送信息对话框 -->
    <el-dialog v-model="sendMessageVisible" title="发送信息" width="600px">
      <div v-if="selectedDevice">
        <el-form label-width="100px">
          <el-form-item label="发送设备">
            <el-input v-model="selectedDevice.code" readonly placeholder="暂无数据" />
          </el-form-item>
          <el-form-item label="发送信息">
            <el-input 
              v-model="sendMessage.content" 
              type="textarea" 
              :rows="4"
              placeholder="请输入要发送的信息" 
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="sendMessageVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSendMessage">发送</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="receiveMessageVisible" title="接收信息" width="600px">
      <div v-if="selectedDevice">
        <el-form label-width="100px">
          <el-form-item label="发送设备">
            <el-input v-model="selectedDevice.code" readonly placeholder="暂无数据" />
          </el-form-item>
          <el-form-item label="接收信息">
            <el-input 
              v-model="receivedMessage.content" 
              type="textarea" 
              :rows="4"
              readonly 
              placeholder="暂无数据" 
              class="receive-message-textarea"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeReceiveMessageDialog">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="authDialogVisible" title="设备认证" width="500px">
      <div v-if="authDeviceData">
        <el-form ref="authFormRef" :model="authForm" label-width="120px">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="authDeviceData.name" disabled />
          </el-form-item>
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="authDeviceData.code" disabled />
          </el-form-item>
          <el-form-item label="客户端编码" prop="clientId">
            <el-input v-model="authDeviceData.clientId" disabled />
          </el-form-item>
          <el-form-item label="认证方式" prop="authMethod" required>
            <el-select v-model="authForm.authMethod" placeholder="请选择认证方式">
              <el-option label="密钥认证" value="DEVICEPASSWORD" />
              <el-option label="证书认证" value="DEVICECERTIFICATE" />
            </el-select>
          </el-form-item>
          <el-form-item label="认证密钥" prop="authPassword" v-if="authForm.authMethod === 'DEVICEPASSWORD'">
        <el-input v-model="authForm.authPassword" placeholder="请输入认证密钥" show-password />
      </el-form-item>
      <el-form-item label="认证证书" prop="certificate" v-if="authForm.authMethod === 'DEVICECERTIFICATE'">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action=""
              :auto-upload="false"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="1"
              accept=".pem,.crt,.cer"
              :http-request="customRequest"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">只能上传 .pem, .crt, .cer 格式的证书文件</div>
              </template>
            </el-upload>
          </el-form-item>
    </el-form>
      </div>
      <template #footer>
        <el-button @click="authDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAuth">确认认证</el-button>
      </template>
    </el-dialog>

    <!-- 设备属性查看对话框 -->
    <el-dialog v-model="propertiesVisible" title="数据操作" width="800px">
      <div v-if="selectedDevice">
        <h4>{{ selectedDevice.name }} - 属性列表</h4>
        <p>所属产品：{{ selectedDevice.productName }}</p>
        <el-table :data="selectedDevice.properties" border style="width: 100%" v-if="selectedDevice.properties && selectedDevice.properties.length > 0">
          <el-table-column prop="displayName" label="属性名称" />
          <el-table-column prop="name" label="属性标识" />
          <el-table-column prop="dataType" label="数据类型">
            <template #default="scope">
              {{ getDataTypeLabel(scope.row.dataType) }}
            </template>
          </el-table-column>
          <el-table-column prop="range" label="数据范围" />
          <el-table-column prop="precision" label="精度" />
          <el-table-column prop="accessMode" label="读取方式">
            <template #default="scope">
              {{ getAccessModeLabel(scope.row.accessMode) }}
            </template>
          </el-table-column>
          <el-table-column prop="value" label="当前值">
            <template #default="scope">
              <el-input v-model="scope.row.value" placeholder="暂无数据" v-if="scope.row.accessMode === 'write' || scope.row.accessMode === 'report'" />
              <span v-else>{{ scope.row.value || '暂无数据' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.accessMode === 'write'" type="primary" size="small" @click="updatePropertyValue(scope.row)">下发</el-button>
              <el-button v-if="scope.row.accessMode === 'report'" type="success" size="small" @click="reportPropertyValue(scope.row)">上发</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-properties">暂无属性配置</div>
      </div>
      <template #footer>
        <el-button @click="propertiesVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessageBox, ElIcon } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { deviceAPI } from '../api/device.js'
import { productAPI } from '../api/product.js'
import notificationService from '../utils/notificationService.js'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

const devices = ref([])
const products = ref([])
const searchQuery = ref('')
const selectedStatus = ref('')
const dialogVisible = ref(false)
const propertiesVisible = ref(false)
const authDialogVisible = ref(false) // 认证对话框显示控制
const receiveMessageVisible = ref(false) // 接收信息对话框显示控制
const sendMessageVisible = ref(false) // 发送信息对话框显示控制
const receivedMessage = reactive({
  content: '' // 接收信息内容
})
const sendMessage = reactive({
  content: '' // 发送信息内容
})
const dialogTitle = ref('新增设备')
const selectedDevice = ref(null)
const authDeviceData = ref(null) // 存储当前需要认证的设备数据
const productProperties = ref([]) // 用于存储选中产品的物模型属性

// 认证表单数据
const authForm = reactive({
  authMethod: 'DEVICEPASSWORD', // 默认使用密钥认证
  authPassword: '',
  certificate: null
})

const fileList = ref([]) // 用于文件上传
const authFormRef = ref()
const formData = reactive({
  id: '',
  code:'',
  name: '',
  productId: '',
  productName: '',
  comment: '',
  accessMethod: 'mqtt',
  authMethod: 'deviceKey',
  authPassword: '',
  status: '',
  hasSelectedProduct: false // 标记是否已选择产品
})

// 切换密码显示状态
const togglePassword = (row, property) => {
  row[property] = !row[property];
};

// 获取数据类型标签
const getDataTypeLabel = (type) => {
  const typeMap = {
    'integer': '整数',
    'double': '双精度',
    'float': '浮点数',
    'int': '整数',
    'string': '字符串',
    'boolean': '布尔值',
    'enum': '枚举'
  }
  return typeMap[type] || type
};

// 获取读取方式的显示标签
const getAccessModeLabel = (mode) => {
  const modeMap = {
    'read': '读',
    'write': '写',
    'report': '上报',
    'read_write': '读写'
  }
  return modeMap[mode] || mode
}

const formRef = ref()
const loading = ref(false)
const productsLoading = ref(false)
const propertyLoading = ref(false)

// 分页相关数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

// 获取设备列表
const fetchDevices = async () => {
  loading.value = true
  try {
    console.log('开始获取设备列表...')
    
    // 传递搜索参数、状态筛选参数和分页参数
    const params = {
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage,
      searchKey: searchQuery.value || '',
      status: selectedStatus.value || ''
    }
    
    try {
      const response = await deviceAPI.getDevices(params)
      console.log('API响应成功，更新数据')
      
      // 灵活处理不同的数据格式
      if (response && response.data) {
        // 检查是否是标准分页格式
        if (response.data.data && response.data.data.records) {
          const result = response.data.data
          devices.value = result.records || []
          pagination.total = result.total || 0
          pagination.pages = result.pages || 0
          pagination.currentPage = result.pageNum || pagination.currentPage
        } else if (Array.isArray(response.data)) {
          // 如果直接返回数组
          devices.value = response.data
          pagination.total = response.data.length
        } else if (response.data.records) {
          // 如果直接在data下有records字段
          devices.value = response.data.records
          pagination.total = response.data.total || 0
          pagination.pages = response.data.pages || 0
          pagination.currentPage = response.data.pageNum || pagination.currentPage
        } else {
          // 其他情况，尝试直接使用data
          devices.value = response.data || []
          pagination.total = Array.isArray(devices.value) ? devices.value.length : 0
        }
        console.log('API设备数据:', devices.value)
      }
      
      // 如果API返回空数据，也不显示测试数据
    } catch (apiError) {
      console.error('API请求失败，使用测试数据:', apiError)
      // 只有API请求失败时才使用测试数据
      devices.value = [
        {
          id: 'TEST001',
          name: '测试设备001',
          productCode: 'PROD-A001',
          productName: '测试产品A',
          status: 'enabled',
          accessMethod: 'mqtt',
          authMethod: 'deviceKey'
        },
        {
          id: 'TEST002',
          name: '测试设备002',
          productCode: 'PROD-B001',
          productName: '测试产品B',
          status: 'disabled',
          accessMethod: 'http',
          authMethod: 'token'
        },
        {
          id: 'TEST003',
          name: '测试设备003',
          productCode: 'PROD-C001',
          productName: '测试产品C',
          status: 'enabled',
          accessMethod: 'modbus',
          authMethod: 'deviceKey'
        }
      ]
      pagination.total = devices.value.length
      notificationService.error('操作失败')
    }
  } catch (error) {
    notificationService.error('操作失败')
    console.error('获取设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取设备列表
onMounted(() => {
  console.log('组件已挂载，开始获取设备列表')
  fetchDevices()
})

// 处理页码变化
const handleCurrentChange = (currentPage) => {
  pagination.currentPage = currentPage
  fetchDevices()
}

// 处理每页条数变化
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  pagination.currentPage = 1 // 重置为第一页
  fetchDevices()
}

// 处理搜索和状态筛选变化
const handleSearch = () => {
  pagination.currentPage = 1 // 搜索时重置为第一页
  fetchDevices()
}

// 获取产品列表 - 使用新的product/choice接口
const fetchProducts = async () => {
  productsLoading.value = true
  try {
    // 使用新的接口获取产品选择列表，传入认证方式和接入方式参数
    // 目前使用默认值，可以根据需要调整
    const response = await productAPI.getProductChoices('deviceKey', 'mqtt')
    // 从response.data.choiceList中获取产品数据
    products.value = response.data?.choiceList || []
  } catch (error) {
    notificationService.error('操作失败')
    console.error('获取产品列表失败:', error)
    // 在API不可用时，提供模拟数据
    products.value = [
      {
        id: 1,
        name: '车削设备',
        authMethod: 'DEVICEPASSWORD',
        authPassword: 'Passw0rd',
        accessMethod: 'MQTT',
        ProductPropertyList: [
          {
            dataRange: '-40~85',
            propertyName: '温度',
            dataType: 'double',
            property: '温度',
            precisions: 1,
            comment: null,
            accessMode: 'read',
            value: '25.6'
          },
          {
            dataRange: '0~100',
            propertyName: '湿度',
            dataType: 'int',
            property: '湿度',
            precisions: 0,
            comment: null,
            accessMode: 'report',
            value: '60'
          },
          {
            dataRange: '0~50',
            propertyName: '风速',
            dataType: 'double',
            property: '风速',
            precisions: 2,
            comment: null,
            accessMode: 'write',
            value: '3.25'
          },
          {
            dataRange: '10000',
            propertyName: '速度',
            dataType: 'integer',
            property: '速度',
            precisions: 1,
            comment: null,
            accessMode: 'read',
            value: '10000'
          },
          {
            dataRange: '1000',
            propertyName: '重量',
            dataType: 'integer',
            property: '重量',
            precisions: 0,
            comment: null,
            accessMode: 'read',
            value: '10000'
          }
        ]
      },
      {
        id: 2,
        name: '起重机',
        authMethod: 'DEVICEPASSWORD',
        authPassword: 'Passw0rd',
        accessMethod: 'MQTT',
        ProductPropertyList: [
          {
            dataRange: '200-300',
            propertyName: '最大起重量',
            dataType: 'integer',
            property: 'Maximum lifting capacity',
            precisions: 1,
            comment: null,
            accessMode: 'read',
            value: '270'
          },
          {
            dataRange: '100',
            propertyName: '车重',
            dataType: 'integer',
            property: 'Vehicle weight',
            precisions: 1,
            comment: null,
            accessMode: 'read',
            value: '100'
          }
        ]
      }
    ]
  } finally {
    productsLoading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增设备'
  Object.assign(formData, {
    id: '',
    code: '',
    name: '',
    productId: '',
    productName: '',
    comment: '',
    accessMethod: 'mqtt',
    authMethod: 'DEVICEPASSWORD',
    authPassword: '',
    status: 'enabled',
    hasSelectedProduct: false // 新增设备时默认不显示认证方式和接入方式输入框
  })
  dialogVisible.value = true
}

// 编辑设备
const editDevice = async (row) => {
  dialogTitle.value = '编辑设备'
  
  // 重置表单数据
  formData.id = row.id
  formData.code = ''
  formData.name = ''
  formData.productId = ''
  formData.productName = ''
  formData.comment = ''
  formData.accessMethod = 'mqtt'
  formData.authMethod = 'DEVICEPASSWORD'
  formData.authPassword = ''
  formData.hasSelectedProduct = false
  
  try {
    const response = await deviceAPI.getDevice(row.id)
    // 只编辑设备特有的信息，不包括物模型属性
    formData.code = response.data.code || ''
    formData.name = response.data.name || ''
    formData.productId = response.data.productId || ''
    formData.productName = response.data.productName || ''
    formData.comment = response.data.comment || ''
    formData.accessMethod = response.data.accessMethod || 'mqtt'
    formData.authMethod = response.data.authMethod || 'DEVICEPASSWORD'
    formData.authPassword = response.data.authPassword || response.data.deviceKey || ''
    formData.status = response.data.status
    formData.hasSelectedProduct = true // 确保设置为true，以便显示物模型属性
    
    // 获取设备的物模型属性列表
    await fetchDeviceProperties(row.id)
  } catch (error) {
    console.error('获取设备详情失败:', error)
    // 如果API调用失败，使用传入的row数据
    formData.code = row.code || ''
    formData.name = row.name || ''
    formData.productId = row.productId || ''
    formData.productName = row.productName || ''
    formData.comment = row.comment || ''
    formData.accessMethod = row.accessMethod || 'mqtt'
    formData.authMethod = row.authMethod || 'DEVICEPASSWORD'
    formData.authPassword = row.authPassword || row.deviceKey || ''
    formData.status = row.status
    formData.hasSelectedProduct = true // 确保设置为true，以便显示物模型属性
    
    // 即使API调用失败，也尝试获取物模型属性
    await fetchDeviceProperties(row.id)
  } finally {
    // 在finally块中显示对话框
    dialogVisible.value = true
  }
}


// 获取设备物模型属性
const fetchDeviceProperties = async (deviceId) => {
  propertyLoading.value = true
  try {
    // 根据deviceAPI.getDeviceProperties的实际方法定义，直接传入deviceId
    const response = await deviceAPI.getDeviceProperties(deviceId)
    // 正确处理API返回的数据结构，从records数组中获取物模型属性
    productProperties.value = response.data.records || []
  } catch (error) {
    console.error('获取设备物模型属性失败:', error)
    // 使用一些模拟数据作为备用
    productProperties.value = [
      {
        property: 'temperature',
        propertyName: '温度',
        dataType: 'double',
        dataRange: '-40~85',
        precisions: 1,
        accessMode: 'report',
        value: '25.5',
        comment: '设备温度'
      },
      {
        property: 'humidity',
        propertyName: '湿度',
        dataType: 'integer',
        dataRange: '0~100',
        precisions: 0,
        accessMode: 'report',
        value: '60',
        comment: '设备湿度'
      }
    ]
  } finally {
    propertyLoading.value = false
  }
}

// 获取产品的物模型属性
const fetchProductProperties = async (productId) => {
  try {
    // 调用接口获取产品的物模型数据
    const response = await productAPI.getProductProperties(productId)
    
    // 支持20000-20003成功状态码范围
        if ((response.code >= 20000 && response.code <= 20003) && response.data && response.data.records) {
      // 处理获取到的物模型数据
      productProperties.value = response.data.records.map(prop => ({
        property: prop.property || '',
        propertyName: prop.propertyName || '',
        dataType: prop.dataType || '',
        dataRange: prop.dataRange || '',
        precisions: prop.precisions || 0,
        accessMode: prop.accessMode || '',
        value: prop.value || '',
        comment: prop.comment || ''
      }))
    } else {
      // 提供模拟数据作为备选
      productProperties.value = [
        {
          property: '温度',
          propertyName: '温度',
          dataType: 'double',
          dataRange: '-40~85',
          precisions: 1,
          accessMode: 'read',
          value: '25.6',
          comment: ''
        },
        {
          property: '湿度',
          propertyName: '湿度',
          dataType: 'int',
          dataRange: '0~100',
          precisions: 0,
          accessMode: 'report',
          value: '60',
          comment: ''
        },
        {
          property: '风速',
          propertyName: '风速',
          dataType: 'double',
          dataRange: '0~50',
          precisions: 2,
          accessMode: 'write',
          value: '3.25',
          comment: ''
        },
        {
          property: '速度',
          propertyName: '速度',
          dataType: 'integer',
          dataRange: '0~10000',
          precisions: 1,
          accessMode: 'read',
          value: '10000',
          comment: ''
        },
        {
          property: '重量',
          propertyName: '重量',
          dataType: 'integer',
          dataRange: '0~1000',
          precisions: 0,
          accessMode: 'read',
          value: '10000',
          comment: ''
        }
      ]
    }
  } catch (error) {
    console.error('获取产品物模型属性失败:', error)
    // 提供模拟数据作为备选
    productProperties.value = [
      {
        property: '温度',
        propertyName: '温度',
        dataType: 'double',
        dataRange: '-40~85',
        precisions: 1,
        accessMode: 'read',
        value: '25.6',
        comment: ''
      },
      {
        property: '湿度',
        propertyName: '湿度',
        dataType: 'int',
        dataRange: '0~100',
        precisions: 0,
        accessMode: 'report',
        value: '60',
        comment: ''
      },
      {
        property: '风速',
        propertyName: '风速',
        dataType: 'double',
        dataRange: '0~50',
        precisions: 2,
        accessMode: 'write',
        value: '3.25',
        comment: ''
      },
      {
        property: '速度',
        propertyName: '速度',
        dataType: 'integer',
        dataRange: '0~10000',
        precisions: 1,
        accessMode: 'read',
        value: '10000',
        comment: ''
      },
      {
        property: '重量',
        propertyName: '重量',
        dataType: 'integer',
        dataRange: '0~1000',
        precisions: 0,
        accessMode: 'read',
        value: '10000',
        comment: ''
      }
    ]
  }
}

// 产品选择变化时，获取产品信息
const onProductChange = (productId) => {
  const product = products.value.find(p => p.id === productId)
  if (product) {
    formData.productName = product.name
    // 设置认证方式
    formData.authMethod = product.authMethod || 'DEVICEPASSWORD'
    // 设置认证密码
    formData.authPassword = product.authPassword || ''
    // 设置接入方式，现在接口返回中有accessMethod字段
    formData.accessMethod = product.accessMethod || 'mqtt'
    // 标记已选择产品，用于显示认证方式和接入方式输入框
    formData.hasSelectedProduct = true
    
    // 直接从产品对象中获取物模型属性列表
    productProperties.value = product.ProductPropertyList || []
  }
}

// 提交表单
const submitForm = async () => {
  if (!formData.name) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  // 仅在新增模式下验证产品选择
  if (!formData.id && !formData.productId) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  if (!formData.authPassword) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  
  loading.value = true
  try {
    // 准备请求数据
    const requestData = {
      code: formData.code,
      name: formData.name,
      productId: formData.productId || formData.productId,
      comment: formData.comment || '',
      accessMethod: formData.accessMethod || 'MQTT',
      authMethod: formData.authMethod || 'DEVICEPASSWORD',
      authPassword: formData.authPassword,
      properties: productProperties.value.map((prop, index) => ({
        id: prop.id || index + 1,
        productId: parseInt(formData.productId) || 1,
        deviceId: formData.id || 2,
        property: prop.property || prop.propertyName,
        propertyName: prop.propertyName || prop.property,
        dataType: prop.dataType,
        dataRange: prop.dataRange || '',
        precisions: prop.precisions || 0,
        accessMode: prop.accessMode || 'read',
        value: prop.value || '',
        comment: prop.comment || '',
        deleted: '0'
      }))
    }
    
    if (formData.id) {
      // 编辑操作 - 使用设备code而不是id
      const response = await deviceAPI.updateDevice(formData.code, requestData)
      // 根据接口返回的type判断成功或失败
      if (response.type === 'SUCCESS' || response.data?.type === 'SUCCESS') {
        notificationService.success(response.message || response.data?.message || '设备更新成功')
      } else {
        notificationService.error(response.message || response.data?.message || '操作失败')
      }
    } else {
      // 新增操作
      await deviceAPI.createDevice(requestData)
      notificationService.success('设备添加成功')
    }
    // 重新获取列表
    await fetchDevices()
    dialogVisible.value = false
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || (formData.id ? '更新设备失败' : '添加设备失败')
    notificationService.error(errorMessage)
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除设备
const deleteDevice = async (id) => {
  ElMessageBox.confirm('确定要删除这个设备吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      await deviceAPI.deleteDevice(id)
      notificationService.success('删除成功')
      // 重新获取列表
      await fetchDevices()
    } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '删除失败'
    notificationService.error(errorMessage)
    console.error('删除失败:', error)
  } finally {
      loading.value = false
    }
  }).catch(() => {
    notificationService.info('已取消删除')
  })
}

// 切换设备状态
const toggleDeviceStatus = async (row) => {
  // 根据数字状态码处理切换逻辑
  let newStatus = 2 // 启用状态码
  let statusText = '启用'
  if (row.status === 2 || row.status === '2' || row.status === '启用') {
    newStatus = 3 // 未启用状态码
    statusText = '未启用'
  }
  try {
    // 使用设备的code而不是id调用API
    const response = await deviceAPI.toggleDeviceStatus(row.code, newStatus)
    
    // 根据接口返回的type判断成功或失败
    if (response.type === 'SUCCESS' || response.data?.type === 'SUCCESS') {
      // 更新本地状态
      row.status = newStatus
      // 显示接口返回的message
      notificationService.success(response.message || response.data?.message || `设备${statusText}成功`)
    } else {
      // 显示错误消息
      notificationService.error(response.message || response.data?.message || '操作失败')
    }
  } catch (error) {
    // 处理网络错误等异常情况
    console.error('切换状态失败:', error)
    notificationService.error('操作失败')
  }
}

// 处理设备认证 - 显示认证对话框
const handleAuthDevice = (row) => {
  // 重置认证表单
  authForm.authMethod = row.authMethod || 'DEVICEPASSWORD' // 默认使用设备的authMethod值
  authForm.authPassword = ''
  authForm.certificate = null
  fileList.value = []
  // 设置当前认证设备数据
  authDeviceData.value = { ...row }
  // 计算并设置客户端编码 clientId = productCode-code
  if (row.productCode && row.code) {
    authDeviceData.value.clientId = `${row.productCode}_${row.code}`
  }
  // 显示认证对话框
  authDialogVisible.value = true
}

// 确认认证
const confirmAuth = async () => {
  // 表单验证
  if (!authForm.authMethod) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  if (authForm.authMethod === 'DEVICEPASSWORD' && !authForm.authPassword) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  if (authForm.authMethod === 'DEVICECERTIFICATE' && fileList.value.length === 0) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }

  loading.value = true
  try {
    // 调用认证接口，使用新的格式
    const response = await deviceAPI.certifyDevice(
      authDeviceData.value.code,
      authDeviceData.value.clientId,
      authForm.authPassword
    )
    
    // 根据接口返回的数据显示消息
    if (response.type === 'SUCCESS') {
      // 认证成功后刷新设备列表
      await fetchDevices()
      notificationService.success(response.message || '设备认证成功')
      authDialogVisible.value = false
    } else {
      // 只要type不是SUCCESS，都显示错误信息
      notificationService.error(response.message || '操作失败')
    }
  } catch (error) {
    notificationService.error('操作失败')
    console.error('设备认证失败:', error)
  } finally {
    loading.value = false
  }
}

// 文件上传相关方法
const handlePreview = (file) => {
  console.log('预览文件:', file)
}

const handleRemove = (file, fileList) => {
  console.log('移除文件:', file, fileList)
}

const beforeRemove = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`)
}

const handleExceed = (files, fileList) => {
  notificationService.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，已自动忽略多余文件`)
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  // 根据状态码返回对应的标签类型
  switch (status) {
    case 2:
    case '2':
    case '启用':
    case 'enabled':
      return 'success'
    case 1:
    case '1':
    case '认证':
      return 'primary'
    case 0:
    case '0':
    case '未认证':
      return 'info'
    case 3:
    case '3':
    case '未启用':
    case 'disabled':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态显示文本
const getStatusLabel = (status) => {
  switch (status) {
    case 2:
    case '2':
    case '启用':
    case 'enabled':
      return '启用'
    case 3:
    case '3':
    case '未启用':
    case 'disabled':
      return '未启用'
    case 1:
    case '1':
    case '认证':
      return '认证'
    case 0:
    case '0':
    case '未认证':
      return '未认证'
    default:
      return '未知'
  }
}

// 获取状态切换按钮文本
const getToggleStatusLabel = (status) => {
  // 只有启用(2)和未启用(3)状态可以切换
  if (status === 2 || status === '2' || status === '启用' || status === 'enabled') {
    return '禁用'
  } else if (status === 3 || status === '3' || status === '未启用' || status === 'disabled') {
    return '启用'
  } else {
    // 对于认证/未认证状态，显示启用或禁用取决于当前状态
    return '启用'
  }
}

// 全局STOMP客户端引用
let stompClient = null;
// 全局消息订阅引用
let messageSubscription = null;

// 处理数据操作下拉菜单命令
const handleDataOperationCommand = async (command, row) => {
  // 深拷贝，避免直接修改原数据
  selectedDevice.value = JSON.parse(JSON.stringify(row))
  
  if (command === 'receive') {
    // 接收信息操作 - 显示接收信息对话框并建立STOMP连接
    receiveMessageVisible.value = true;
    
    // 初始化连接
    initStompConnection(row);
    
  } else if (command === 'send') {
    // 发送信息操作 - 显示发送信息对话框
    sendMessage.content = '' // 清空上次的发送内容
    sendMessageVisible.value = true
  }
}

// 初始化STOMP连接
const initStompConnection = (row) => {
  try {
    // 先关闭之前的连接
    closeStompConnection();
    
    // 清空接收内容
    receivedMessage.content = '正在连接设备...\n';
    
    // 连接后端STOMP端点 - SockJS需要使用HTTP协议而不是WebSocket协议
    const httpProtocol = window.location.protocol; // 直接使用当前页面的协议(http:或https:)
    // 注意：实际部署时需要确保后端有对应的STOMP端点
    const sockjsUrl = `http://localhost:8080/mqtt-websocket`; // 使用正确的端点
    
    // 添加调试信息
    console.log('尝试连接STOMP服务:', sockjsUrl);
    
    const socket = new SockJS(sockjsUrl); // 用SockJS兼容不同浏览器
    
    // 监听socket错误
    socket.onclose = (e) => {
      console.error('SockJS连接关闭:', e);
    };
    
    socket.onerror = (e) => {
      console.error('SockJS连接错误:', e);
      if (e.code) {
        receivedMessage.content += `\n❌ SockJS错误码: ${e.code} - ${e.message || '未知错误'}（${new Date().toLocaleTimeString()}）\n`;
      }
    };
    
    // 创建STOMP客户端
    stompClient = Stomp.over(socket);
    // 启用调试日志以便更好地排查问题
    stompClient.debug = (str) => {
      console.log('STOMP调试:', str);
    };

    // 连接STOMP服务
    stompClient.connect({}, 
      // 连接成功回调
      (frame) => {
        receivedMessage.content += `\n✅ 成功连接到设备消息服务（${new Date().toLocaleString()}）\n`;
        receivedMessage.content += `设备名称: ${row.name || '未知'}\n`;
        receivedMessage.content += `设备编码: ${row.code || '未知'}\n`;
        receivedMessage.content += '\n📨 等待接收设备消息...\n';

        // 订阅指定设备的消息通道
        const deviceTopic = row.code || 'device000001';
        const subscribePath = `/topic/mqtt/${deviceTopic}`; // 与后端推送通道完全对齐
        messageSubscription = stompClient.subscribe(subscribePath, 
          // 接收消息回调
          (message) => {
            handleReceivedMessage(message.body); // 处理收到的消息
          },
          // 订阅的额外参数
          { 'content-type': 'application/json' }
        );
      },
      // 连接失败回调（自动重连，但限制重试次数）
      (error) => {
        // 增强错误信息显示
        let errorMsg = '未知错误';
        if (typeof error === 'string') {
          errorMsg = error;
        } else if (error.message) {
          errorMsg = error.message;
        } else if (error.headers) {
          errorMsg = `状态码: ${error.headers.message || '未知'}`;
        }
        
        receivedMessage.content += `\n❌ 连接失败: ${errorMsg}（${new Date().toLocaleTimeString()}）\n`;
        console.error('STOMP连接失败:', error);
        
        // 检测是否是端点不存在的情况
        if (errorMsg.includes('404') || errorMsg.includes('未找到')) {
          receivedMessage.content += '\n⚠️ 提示: 可能后端STOMP服务未启动或端点路径不正确\n';
        }
        
        // 显示模拟数据作为备用
        if (!receivedMessage.content.includes('使用模拟数据')) {
          showMockData(row);
        }
      }
    );
  } catch (err) {
    console.error('初始化STOMP连接异常:', err);
    receivedMessage.content += `\n❌ 初始化连接异常: ${err.message || '未知错误'}（${new Date().toLocaleTimeString()}）\n`;
    
    // 显示模拟数据作为备用
    showMockData(row);
  }
};

// 显示模拟数据函数
const showMockData = (row) => {
  receivedMessage.content += `\n使用模拟数据显示:\n`;
  receivedMessage.content += `设备 ${row.name || '未知'} (${row.code || '未知'}) 状态正常\n` +
                           `时间: ${new Date().toLocaleString()}\n` +
                           `接入方式: ${row.accessMethod || '未知'}\n` +
                           `当前状态: ${getStatusLabel(row.status)}\n`;
};

// 处理收到的MQTT消息（格式化显示）
const handleReceivedMessage = (messageBody) => {
  try {
    // 解析后端推送的JSON消息
    const messageData = JSON.parse(messageBody);
    const receiveTime = new Date(messageData.timestamp || Date.now()).toLocaleTimeString();
    
    receivedMessage.content += `\n📩 [${receiveTime}] 设备消息（主题：${messageData.topic || '未知'}）\n`;
    
    // 格式化显示消息内容
    if (messageData.message) {
      // 如果消息有message字段，显示其内容
      receivedMessage.content += `消息来源: ${messageData.source || '未知'}\n`;
      receivedMessage.content += `消息内容: ${JSON.stringify(messageData.message, null, 2)}\n`;
    } else {
      // 否则显示整个消息对象
      receivedMessage.content += `消息内容: ${JSON.stringify(messageData, null, 2)}\n`;
    }
  } catch (err) {
    // 非JSON格式消息（异常情况）
    receivedMessage.content += `\n📩 [${new Date().toLocaleTimeString()}] 原始消息: \n${messageBody}\n`;
  }

  // 自动滚动到文本框底部
  setTimeout(() => {
    const textarea = document.querySelector('.receive-message-textarea');
    if (textarea) textarea.scrollTop = textarea.scrollHeight;
  }, 100);
};

// 关闭STOMP连接和清理资源
const closeStompConnection = () => {
  // 取消消息订阅
  if (messageSubscription) {
    messageSubscription.unsubscribe();
    messageSubscription = null;
  }
  // 断开STOMP连接
  if (stompClient && stompClient.connected) {
    stompClient.disconnect(() => {
      receivedMessage.content += `\n❌ 连接已关闭（${new Date().toLocaleTimeString()}）\n`;
    });
    stompClient = null;
  }
};

// 关闭接收信息对话框并清理STOMP连接
const closeReceiveMessageDialog = () => {
  // 关闭STOMP连接
  closeStompConnection();
  // 隐藏对话框
  receiveMessageVisible.value = false;
};

// 提交发送信息
const submitSendMessage = () => {
  if (!sendMessage.content.trim()) {
    notificationService.warning('请输入要发送的信息')
    return
  }
  
  // 这里可以添加发送信息的API调用逻辑
  // 暂时使用模拟数据展示
  notificationService.success(`信息已成功发送到设备 ${selectedDevice.value.code}`)
  
  // 关闭对话框
  sendMessageVisible.value = false
}
const showDataOperation = async (row) => {
  // 深拷贝，避免直接修改原数据
  selectedDevice.value = JSON.parse(JSON.stringify(row))
  
  propertyLoading.value = true
  try {
    const response = await deviceAPI.getDeviceProperties(row.id)
    if (response.data && response.data.length > 0) {
      // 更新属性值
      if (selectedDevice.value.properties) {
        selectedDevice.value.properties.forEach(prop => {
          const newProp = response.data.find(p => p.name === prop.name)
          if (newProp && newProp.value !== undefined) {
            prop.value = newProp.value
          }
        })
      }
    }
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '获取设备属性值失败'
    notificationService.error(errorMessage)
    console.error('获取设备属性值失败:', error)
  } finally {
    propertyLoading.value = false
    propertiesVisible.value = true
  }
}

// 下发属性值
const updatePropertyValue = async (property) => {
  try {
    const response = await deviceAPI.updateDeviceProperty(selectedDevice.value.id, {
      name: property.name,
      value: property.value
    })
    // 支持20000-20003成功状态码范围
        if (response.code === 200 || (response.code >= 20000 && response.code <= 20003)) {
      notificationService.success('属性下发成功')
    } else {
      notificationService.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('下发属性值失败:', error)
    notificationService.error('操作失败')
  }
}

// 上发属性值
const reportPropertyValue = async (property) => {
  try {
    // 检查deviceAPI是否有reportDeviceProperty方法，如果没有则使用模拟数据
    let response;
    if (deviceAPI.reportDeviceProperty) {
      response = await deviceAPI.reportDeviceProperty(selectedDevice.value.id, {
        name: property.name,
        value: property.value
      })
    } else {
      // 模拟成功响应
      response = { code: 200000, message: '模拟响应：属性上发成功' }
    }
    
    // 支持20000-20003成功状态码范围
        if (response.code === 200 || (response.code >= 20000 && response.code <= 20003)) {
      notificationService.success('属性上发成功')
    } else {
      notificationService.error(response.message || '操作失败')
    }
  } catch (error) {
      console.error('上发属性值失败:', error)
      notificationService.error('操作失败')
    }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDevices()
  fetchProducts()
})

// 组件卸载时关闭连接（防止内存泄漏）
onUnmounted(() => {
  closeStompConnection();
});
</script>

<style scoped>
.device-management {
  padding: 0;
  min-height: calc(100vh - 130px);
  background: white;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 管理卡片 */
.management-card {
  width: 100%;
  background: white;
  position: relative;
  z-index: 1;
  overflow: hidden;
  border: none;
  box-shadow: none;
  margin: 0;
}

.card-header {
  background: #667eea;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

/* 按钮样式 */
.primary-button {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.primary-button:hover {
  background: linear-gradient(90deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  gap: 15px;
  padding: 20px 24px;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #ebeef5;
  justify-content: space-between;
}

.search-input {
  width: 280px;
  max-width: 100%;
}

.search-select {
  width: 180px;
  max-width: 100%;
}

/* 搜索框样式 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

/* 卡片样式 */

:deep(.el-input__wrapper) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

/* 表格样式 */
:deep(.el-table) {
  --el-table-header-bg-color: rgba(102, 126, 234, 0.1);
  --el-table-header-text-color: #667eea;
  width: calc(100% - 40px);
  flex: 1;
  margin: 0 20px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 0;
  --el-table-border-color: #ebeef5;
  --el-table-row-hover-bg-color: rgba(102, 126, 234, 0.05);
  overflow: visible;
}

/* 确保表格头部颜色完全填充 */
:deep(.el-table__header-wrapper) {
  width: 100% !important;
  border-radius: 0;
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__header) {
  width: 100% !important;
  border-radius: 0;
}

/* 表格主体区域边框 */
:deep(.el-table__body-wrapper) {
  border-right: 1px solid #ebeef5;
}

/* 表格单元格边框 */
:deep(.el-table__row td.el-table__cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 表格头部单元格边框 */
:deep(.el-table__header th.el-table__cell) {
  background-color: rgba(102, 126, 234, 0.1) !important;
  padding: 12px 0;
  text-align: center;
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 覆盖Element UI默认样式，确保右侧固定列也有边框 */
:deep(.el-table__fixed-right) {
  box-shadow: none !important;
  border-left: 1px solid #ebeef5;
}

/* 确保最后一行也有底边框 */
:deep(.el-table__row:last-child td.el-table__cell) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

:deep(.el-table__row:hover) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 分页样式 */
.pagination-container {
  padding: 20px 24px 20px calc(24px + 20px);
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

/* 对话框样式 */
.el-dialog {
  max-width: 90vw;
  margin: 20px auto;
  width: auto !important;
}

:deep(.el-dialog__header) {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 8px 8px 0 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: bold;
}

:deep(.el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background: white;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  background: #f9f9f9;
  border-radius: 0 0 8px 8px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  flex-wrap: nowrap;
  gap: 2px; /* 减小按钮间距 */
  justify-content: center;
  align-items: center;
  height: 40px;
  padding: 2px; /* 添加少量内边距 */
  margin: 0;
}

/* 无数据提示样式 */
.no-properties {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}
</style>